package com.wss.lsl.test.driven.part1;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wss.lsl.test.driven.exception.MissingValueException;

public class Template {

	private String temp;
	private Map<String, String> variableMap;

	public Template(String temp) {
		variableMap = new HashMap<String, String>();
		this.temp = temp;
	}

	public void set(String key, String value) {
		variableMap.put(key, value);
	}

	public String evaluate() throws MissingValueException {
		TemplateParse parse = new TemplateParse();
		List<Segment> segments = parse.parseSegments(temp);

		return concatenate(segments);
	}

	/**
	 * 渲染。做的只是一件事
	 * 
	 * @param segments
	 * @return
	 */
	private String concatenate(List<Segment> segments) {
		StringBuilder result = new StringBuilder();
		for (Segment segment : segments) {
			result.append(segment.evaluate(variableMap));
		}
		return result.toString();
	}

}
